package com.baba.bracelet.utils;

import com.google.common.collect.Maps;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wulongbo
 * @version 1.0
 * @date 2020/6/5 9:23
 * @description
 */
public class OkHttpUtil {

    public static void main(String[] args) throws IOException {

        Map<String,Object> parmMap=new HashMap<String, Object>();
        parmMap.put("customerId","baba");
        parmMap.put("secretKey","secretKey");

        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put("customerId","xxx999");
        headerMap.put("secretKey","xxxxxx212bc7c939bb");

//        // 发送 GET 请求
//        String s = doGetHttpRequest("http://123.56.73.147:8012/openApi/getToken",parmMap);
//        System.out.println(s);

        String post=doPostHttpRequest2("http://123.56.73.147:8012/openApi/getToken",parmMap);
        System.out.println(post);

        //发送 POST 请求（注意发送的数据格式，如果数据格式发送错误会返回400错误）
        /*****这里有个大坑啊，如果参数怎么都接收不到就看看那个传的参数格式↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓******/
        //String sr = sendPost("https://a1.easemob.com/1108190822148388/manhaotestone/token", "key=123&v=456");
        //System.out.println(sr);
    }

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtil.class);

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType
            .parse("image/png;charset=utf-8");
    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType
            .parse("text/x-markdown; charset=utf-8");


    /**
     * 不会开启异步线程。
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return client.newCall(request).execute();
    }

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback) {
        client.newCall(request).enqueue(responseCallback);
    }

    /**
     * 根据url地址获取数据
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGetHttpRequest(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    public static String doGetHttpRequest(String url, Map<String, Object> params) {
        // 设置HTTP请求参数
        String string = null;
        url += getParams(params);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            string = response.body().string();
        } catch (Exception e) {
            log.error("调用三方接口出错", e);
        }
        return string;
    }



    public static String doGetHttpRequest(String url, Map<String, Object> params, Map<String, String> headMap) {
        // 设置HTTP请求参数
        String result = null;
        url += getParams(params);
        Headers setHeaders = SetHeaders(headMap);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).headers(setHeaders).build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String string = response.body().string();
            result = String.valueOf(MEDIA_TYPE_MARKDOWN.parse(string));
        } catch (Exception e) {
            log.error("调用三方接口出错", e);
        }
        return result;
    }

    public static String getParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer("?");
        if (!params.isEmpty()) {
            int i=1;
            for (Map.Entry<String, Object> item : params.entrySet()) {
                Object value = item.getValue();
                /**
                 * 判断Object对象为空或空字符串
                 * @param obj
                 * @return
                 */
                if (StringUtils.isNotBlank(ObjectUtils.toString(value,""))) {
                    sb.append(item.getKey());
                    sb.append("=");
                    sb.append(value);
                    if(params.size()>i){
                        sb.append("&&");
                        i++;
                    }
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    public static Headers SetHeaders(Map<String, String> headersParams) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (!headersParams.isEmpty()) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                headersbuilder.add(key, headersParams.get(key));
            }
        }
        headers = headersbuilder.build();
        return headers;
    }




    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String doPostHttpRequest(String url, String json)
            throws IOException {
        Request request = new Request.Builder().url(url)
                .post(RequestBody.create(JSON, json)).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param params json
     * @return  json  提交的参数为key=value&key1=value1的形式
     * @throws IOException
     */
    public static String doPostHttpRequest2(String url, Map<String, Object> params)
            throws IOException {
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, json);
//        Request request = new Request.Builder().url(url).post(body)
//                .addHeader("content-type", "application/json").build();
//
//        Response response = client.newCall(request).execute();
//        if (!response.isSuccessful()) {
//
//            throw new IOException("Unexpected code " + response);
//        }
//        return response.body().string();
        String result = null;
        String json=getParams(params);
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = httpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String doPostImgHttpRequest(String url, File file)
            throws IOException {
        RequestBody requestBody =  new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("buffer", file.getName(),
                        RequestBody.create(MEDIA_TYPE_PNG, file)).build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }
}
